﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace Sidvall.UI.Wpf.Converters
{
	public class BooleanToVisibilityConverter : IValueConverter
	{
		#region Public Members

		#region Collapsed

		private bool _Collapsed = true;
		public bool Collapsed
		{
			get
			{
				return _Collapsed;
			}
			set
			{
				_Collapsed = value;
			}
		}

		#endregion
		#region Inverted

		private bool _Inverted = false;
		public bool Inverted
		{
			get
			{
				return _Inverted;
			}
			set
			{
				_Inverted = value;
			}
		}

		#endregion
		#region Not

		private bool _Not = false;
		public bool Not
		{
			get
			{
				return _Not;
			}
			set
			{
				_Not = value;
			}
		}

		#endregion

		#region Convert

		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			return Inverted ? VisibilityToBool(value) : BoolToVisibility(value);
		}

		#endregion
		#region ConvertBack

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			return Inverted ? BoolToVisibility(value) : VisibilityToBool(value);
		}

		#endregion

		#endregion
		#region Private Members

		#region VisibilityToBool

		private object VisibilityToBool(object value)
		{
			if (!(value is Visibility))
				return DependencyProperty.UnsetValue;
			switch ((Visibility)value)
			{
				case Visibility.Collapsed:
				case Visibility.Hidden:
					return this.Not;
				default:
					return !this.Not;
			}
		}

		#endregion
		#region BoolToVisibility

		private object BoolToVisibility(object value)
		{
			if (value == null)
			{
				if (this.Collapsed)
					return Visibility.Collapsed;
				return Visibility.Hidden;
			}
			if (!(value is bool))
				return DependencyProperty.UnsetValue;
			if (this.Collapsed)
				return ((bool)value ^ Not) ? Visibility.Visible : Visibility.Collapsed;
			return ((bool)value ^ Not) ? Visibility.Visible : Visibility.Hidden;
		}

		#endregion

		#endregion
	}
}
